<template>
  <div class="home-page">
    <!-- Hero 区域 -->
    <section class="hero-section py-20 bg-gradient-to-br from-primary-50 to-purple-50 dark:from-gray-900 dark:to-gray-800">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center max-w-4xl mx-auto">
          <h1 class="text-5xl md:text-6xl font-bold mb-6">
            <span class="gradient-text">发现最好用的开发工具</span>
          </h1>
          <p class="text-xl text-gray-600 dark:text-gray-300 mb-8">
            精选 1000+ 开发者工具，提升你的开发效率
          </p>
          
          <!-- 搜索框 -->
          <div class="max-w-2xl mx-auto mb-8">
            <div class="relative">
              <input
                type="text"
                v-model="searchKeyword"
                placeholder="搜索工具、框架、库..."
                class="input pl-12 pr-4 py-4 text-lg"
                @keyup.enter="handleSearch"
              />
              <Icon
                name="heroicons:magnifying-glass"
                class="absolute left-4 top-1/2 transform -translate-y-1/2 w-6 h-6 text-gray-400"
              />
            </div>
          </div>

          <!-- 统计数据 -->
          <div class="grid grid-cols-3 gap-8 max-w-2xl mx-auto">
            <div>
              <div class="text-3xl font-bold text-primary-600">1000+</div>
              <div class="text-gray-600 dark:text-gray-400">开发工具</div>
            </div>
            <div>
              <div class="text-3xl font-bold text-primary-600">50+</div>
              <div class="text-gray-600 dark:text-gray-400">工具分类</div>
            </div>
            <div>
              <div class="text-3xl font-bold text-primary-600">10K+</div>
              <div class="text-gray-600 dark:text-gray-400">开发者</div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 推广工具 -->
    <section v-if="sponsoredTools?.length" class="py-12 border-b border-gray-200 dark:border-gray-800">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold flex items-center gap-2">
            <Icon name="heroicons:fire" class="text-orange-500" />
            推荐工具
          </h2>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
          <ToolCard
            v-for="tool in sponsoredTools"
            :key="tool.id"
            :tool="tool"
            :is-sponsored="true"
          />
        </div>
      </div>
    </section>

    <!-- 特色工具 -->
    <section class="py-12">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold flex items-center gap-2">
            <Icon name="heroicons:star" class="text-yellow-500" />
            特色工具
          </h2>
          <NuxtLink to="/tools" class="text-primary-600 hover:text-primary-700 flex items-center gap-1">
            查看全部
            <Icon name="heroicons:arrow-right" class="w-4 h-4" />
          </NuxtLink>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <ToolCard
            v-for="tool in featuredTools"
            :key="tool.id"
            :tool="tool"
          />
        </div>
      </div>
    </section>

    <!-- 热门分类 -->
    <section class="py-12 bg-gray-50 dark:bg-gray-900/50">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <h2 class="text-2xl font-bold mb-6">热门分类</h2>
        
        <!-- 调试信息 -->
        <div v-if="!categories || categories.length === 0" class="text-center py-8">
          <p class="text-gray-500">暂无分类数据</p>
          <p class="text-sm text-gray-400 mt-2">Categories: {{ categories }}</p>
        </div>
        
        <div v-else class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <CategoryCard
            v-for="category in categories"
            :key="category.id"
            :category="category"
          />
        </div>
      </div>
    </section>

    <!-- 热门工具 -->
    <section class="py-12">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold flex items-center gap-2">
            <Icon name="heroicons:chart-bar" class="text-green-500" />
            热门工具
          </h2>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <ToolCard
            v-for="tool in popularTools"
            :key="tool.id"
            :tool="tool"
          />
        </div>
      </div>
    </section>

    <!-- 精选文章 -->
    <section v-if="featuredArticles?.length" class="py-12 bg-gray-50 dark:bg-gray-900/50">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold flex items-center gap-2">
            <Icon name="heroicons:newspaper" class="text-blue-500" />
            精选文章
          </h2>
          <NuxtLink to="/articles" class="text-primary-600 hover:text-primary-700 flex items-center gap-1">
            查看全部
            <Icon name="heroicons:arrow-right" class="w-4 h-4" />
          </NuxtLink>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <NuxtLink
            v-for="article in featuredArticles"
            :key="article.id"
            :to="`/articles/${article.slug}`"
            class="card p-6 hover:shadow-lg transition-shadow group"
          >
            <!-- 封面图 -->
            <div v-if="article.coverImage" class="mb-4 rounded-lg overflow-hidden">
              <img
                :src="article.coverImage"
                :alt="article.title"
                class="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300"
              />
            </div>
            
            <!-- 文章信息 -->
            <div class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-2">
              <Icon name="heroicons:calendar" class="w-4 h-4" />
              <time>{{ formatDate(article.publishedAt) }}</time>
              <span>•</span>
              <Icon name="heroicons:eye" class="w-4 h-4" />
              <span>{{ article.views }} 浏览</span>
            </div>

            <h3 class="text-xl font-semibold mb-2 group-hover:text-primary-600 transition-colors line-clamp-2">
              {{ article.title }}
            </h3>
            
            <p class="text-gray-600 dark:text-gray-400 line-clamp-3 mb-4">
              {{ article.excerpt }}
            </p>

            <!-- 分类和标签 -->
            <div class="flex items-center gap-2 flex-wrap">
              <span v-if="article.category" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-200">
                {{ article.category }}
              </span>
              <span
                v-for="tag in article.tags?.slice(0, 2)"
                :key="tag"
                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
              >
                {{ tag }}
              </span>
            </div>
          </NuxtLink>
        </div>
      </div>
    </section>

    <!-- CTA 区域 -->
    <section class="py-20 bg-gradient-to-r from-primary-600 to-purple-600 text-white">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8 text-center">
        <h2 class="text-4xl font-bold mb-4">升级会员，解锁更多功能</h2>
        <p class="text-xl mb-8 text-white/90">
          无广告浏览、无限收藏、AI 推荐、独家资源
        </p>
        <NuxtLink to="/pricing" class="btn btn-secondary">
          <Icon name="heroicons:sparkles" />
          查看会员套餐
        </NuxtLink>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import type { Tool, Category, Article } from '~/types'

const searchKeyword = ref('')
const { getPopularTools, getFeaturedTools, getSponsoredTools } = useTools()
const { getCategories } = useCategories()
const { getArticles } = useArticles()

// 获取数据
const { data: popularTools } = await useAsyncData<Tool[]>('popularTools', () => getPopularTools(8))
const { data: featuredTools } = await useAsyncData<Tool[]>('featuredTools', () => getFeaturedTools(8))
const { data: sponsoredTools } = await useAsyncData<Tool[]>('sponsoredTools', () => getSponsoredTools(5))

// 获取分类数据
const { data: categories } = await useAsyncData<Category[]>(
  'categories',
  async () => {
    try {
      const all = await getCategories()
      console.log('📦 获取到的分类数据:', all)
      return all.slice(0, 12) // 只显示前 12 个分类
    } catch (error) {
      console.error('❌ 获取分类失败:', error)
      return []
    }
  },
  {
    // 每次都重新获取，不使用缓存
    server: true,
    lazy: false,
  }
)

// 获取精选文章
const { data: featuredArticles } = await useAsyncData<Article[]>('featuredArticles', async () => {
  const response = await getArticles({
    status: 'published',
    sortBy: 'latest',
    limit: 3,
  })
  return response.data
})

/**
 * 处理搜索
 */
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    navigateTo(`/tools?search=${encodeURIComponent(searchKeyword.value)}`)
  }
}

/**
 * 格式化日期
 */
const formatDate = (date?: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}

// SEO Meta 标签和结构化数据
const config = useRuntimeConfig()
const siteUrl = config.public.siteUrl || 'http://localhost:3000'
const title = 'DevToolsNav - 开发者工具导航 | 精选1000+开发工具'
const description = '精选 1000+ 开发者工具，包括前端框架、后端工具、AI 工具、设计工具、在线工具等，帮助开发者提升开发效率。免费工具导航平台，开发者必备。'

// 使用 SEO composable 生成结构化数据
const { generateWebsiteSchema, generateOrganizationSchema } = useSEO()

useHead({
  title,
  meta: [
    // 基本 Meta
    { name: 'description', content: description },
    { name: 'keywords', content: '开发者工具,开发工具导航,前端工具,后端工具,AI工具,在线工具,开发效率,程序员工具,编程工具' },
    { name: 'author', content: 'DevToolsHub' },
    
    // Open Graph (用于社交媒体分享)
    { property: 'og:type', content: 'website' },
    { property: 'og:title', content: title },
    { property: 'og:description', content: description },
    { property: 'og:url', content: siteUrl },
    { property: 'og:site_name', content: 'DevToolsHub' },
    { property: 'og:locale', content: 'zh_CN' },
    
    // Twitter Card
    { name: 'twitter:card', content: 'summary_large_image' },
    { name: 'twitter:title', content: title },
    { name: 'twitter:description', content: description },
    
    // 移动端优化
    { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    { name: 'theme-color', content: '#6366f1' },
    
    // 搜索引擎验证 (上线后添加)
    // { name: 'baidu-site-verification', content: 'YOUR_BAIDU_CODE' },
    // { name: 'google-site-verification', content: 'YOUR_GOOGLE_CODE' },
  ],
  link: [
    { rel: 'canonical', href: siteUrl },
  ],
  // 添加结构化数据 (Schema.org)
  script: [
    {
      type: 'application/ld+json',
      innerHTML: JSON.stringify(generateWebsiteSchema()),
    },
    {
      type: 'application/ld+json',
      innerHTML: JSON.stringify(generateOrganizationSchema()),
    },
  ],
})
</script>


